package com.caixin.api;

import com.alibaba.fastjson.JSON;
import com.caixin.common.exception.GlobalException;
import com.caixin.common.response.ApiResult;
import com.caixin.common.response.CommonResultEnum;
import com.caixin.service.user.UserCmdService;
import com.caixin.service.user.UserQueryService;
import com.caixin.service.user.command.UserAddCmd;
import com.caixin.service.user.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Map;
import java.util.Optional;

/**
 * 系统用户
 *
 * @author Administrator
 * @version 1.0.0
 * @createTime 2021年12月11日 13:34
 */
@RestController
@RequestMapping("/user")
@Api(tags = "系统管理")
@Slf4j
public class UserController {

    @Autowired
    UserCmdService userCmdService;

    @Autowired
    UserQueryService userQueryService;

    @ApiOperation(value = "保存用户")
    @PostMapping("save")
    @ResponseBody
    public ApiResult save(@RequestBody @Validated UserAddCmd cmd) {
        userCmdService.addUser(cmd);
        return ApiResult.success();
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("detailed/{id}")
    @ResponseBody
    public ApiResult find(@ApiParam("用户主键Id") @NotNull(message = "用户Id不能为空！") @PathVariable("id") Long id)
    {
        Optional<UserDTO> userDto = Optional.ofNullable(userQueryService.findUserById(id));
        if(!userDto.isPresent())
        {
            throw new GlobalException(CommonResultEnum.NOTFOUND);
        }

        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(userDto), Map.class);
        return ApiResult.success(userDto);
    }
}
